#!/usr/bin/lua
-- Simple informal test
--
--
function usage()
    print("Usage: " .. arg[0] .. " [sqlite3|postgresql]")
    print("or")
    print("Usage: luajit " .. arg[0] .. " [sqlite3|postgresql]")
    os.exit()
end

local db = arg[1]
local testfile = "/tmp/dbtest.sqlite3"
local conninfo = "dbname=minetest"

local dbtypes = {
    sqlite3    = true,
    postgresql = true
}

if db == nill then
    usage()
end

if dbtypes[db] ~= true then
    usage()
end

package.path = package.path .. ';' .. './packages/?.lua'

print("Start dbtable test.")
print("Database Type: " .. db)
print("")

print("local test = require(\"dbtable\").new({")
print("    db   = \"" .. db .. "\",")
print("    name = \"test\",")

if db == "sqlite3" then
    print("    file = \"" .. testfile .. "\"")
else
    print("    connection = \"" .. conninfo .. "\"")
end

print("})")

local test = require("dbtable").new({
    db         = db,
    name       = "test",
    connection = conninfo,
    file       = testfile
})


print("")
print("__newindex")
print("This set just sets values in the database using __newindex. There is no")
print("response expected.")
print("test[1] = \"a\"")
print("test[2] = \"b\"")
print("test[3] = \"c\"")
print("test[5] = \"e\"")

test[1] = "a"
test[2] = "b"
test[3] = "c"
test[5] = "e"

print("")
print("__index")
print("Print the values from the __newindex test using the __index method.")
print("Expect ...")
print("a")
print("b")
print("c")
print("e")
print("")
print("Results ...")
print(test[1])
print(test[2])
print(test[3])
print(test[5])

print("")
print("__pairs")
print("Fails for luajit")
print("Expect ...")
print("1 : a")
print("2 : b")
print("3 : c")
print("5 : e")
print("")
print("Results ...")

for key, value in pairs(test) do
    print(string.format("%s : %s", key, value))
end

print("")
print("__ipairs")
print("Fails for luajit")
print("Expect ...")
print("1 : a")
print("2 : b")
print("3 : c")
print("")
print("Results ...")

for key, value in ipairs(test) do
    print(string.format("%s : %s", key, value))
end

-- 
-- Not yet supported by lua5.2 or luajit
-- print("")
-- print("__next")
--
-- for k,v in next, test do print(k,v) end

print("")
print("Fails for luajit")
print("__len")

print("Expect: 4")
print("Result: " .. #test)

print("")
print("len()")
print("Expect: 4")
print("Result: " .. test:len())

print("")
print("__call")
print("Expect: foo")
test("foo")
print("Result: " .. test[4])

if db == "postgresql" then
    test:drop()
end

test = nil

if db == "sqlite3" then
    os.remove(testfile)
end

print("")
print("End dbtable test.")
